package com.matriq.cloudmanager.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLDecoder;

import android.content.Context;
import android.util.Log;
import net.lgpage.http.ExceptionAsyncTask;


public abstract class DownloadTask extends ExceptionAsyncTask<File> {

	protected String url;
	protected String dir;
	protected String filename;
	protected Long itemId;
	
	public DownloadTask(Context context,Long itemId, String url, String dir, String filename) {
		super(context);
		this.url = url;
		this.dir = dir;
		this.filename = filename;
		this.itemId=itemId;
	}

	public long getCurrentPostion() {
		return currentPostion;
	}

	public long getLength() {
		return length;
	}

	public Long getItemId() {
		return itemId;
	}

	public void setItemId(Long itemId) {
		this.itemId = itemId;
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public String getDir() {
		return dir;
	}

	public void setDir(String dir) {
		this.dir = dir;
	}

	public String getFilename() {
		return filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public boolean isStopflag() {
		return stopflag;
	}


	@Override
	public void onException(Exception e) {
		super.onException(e);
	}

	@Override
	public File doInBackgroundX(String... ss) throws Exception {
		return download(url, dir, filename);
	}

	public String getFileName(HttpURLConnection conn) {
		String fn = null;
		try {
			fn = URLDecoder.decode(conn.getURL().toString(), "UTF-8");
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			filename =  fn.substring(fn.lastIndexOf("/") + 1);
			return filename;
		} catch (Exception e) {
			return null;
		}
	}
	public void onProgressChange(long progress, long maxlength){
		
	}


	boolean stopflag = false;

	/*private File download(String url, String dir, String filename) throws Exception{
		long position = 0;
		HttpURLConnection conn = null;
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
			conn.setRequestMethod("GET");
		} catch (Exception e) {
			throw e;
		}
		conn.setConnectTimeout(5000);
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		long length = conn.getContentLength();
		if (filename == null) {
			filename = getFileName(conn);
		}
		File fdir = new File(dir);
		if(!fdir.exists())fdir.mkdirs();
		String path = dir + filename;
		RandomAccessFile file = null;
		try {
			file = new RandomAccessFile(path, "rwd");
			file.setLength(length);
			file.seek(position);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		long currentPostion = position;
		InputStream is = null;
		try {
			is = conn.getInputStream();
			int len;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer)) != -1) {
				if (stopflag) {
					is.close();
					onCancelled();
					file.close();
					return null;
				}
				file.write(buffer, 0, len);
				currentPostion += len;
				onProgressChange(currentPostion, length);
			}
			is.close();
			File res = new File(path);
			return res;
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			try {
				file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return null;
	}*/
	long currentPostion;
	long length;
	public File download(String url, String dir, String filename) throws IOException {
		long position = 0;
		HttpURLConnection conn = null;
		Log.e("haha", "download"+" - "+url);
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
		} catch (MalformedURLException e3) {
			throw e3;
		} catch (IOException e3) {
			throw e3;
		}
		if (filename == null) {
			filename = getFileName(conn);
		}
		File fdir = new File(dir);
		boolean bl = fdir.mkdirs();
		String path = dir + "/" + filename;
		File positionFile = new File(path + ".txt");
		try {
			BufferedReader br = new BufferedReader(new FileReader(positionFile));
			try {
				String line = br.readLine();
				position = Long.parseLong(line);
			} catch (IOException | NumberFormatException e) {
				position = 0;
			} finally {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} catch (FileNotFoundException e2) {
			position = 0;
		}
		currentPostion = position;
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		conn.setReadTimeout(10000);
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		length = conn.getContentLength();
		conn.disconnect();
		try {
			conn = (HttpURLConnection) new URL(url).openConnection();
		} catch (MalformedURLException e3) {
			throw e3;
		} catch (IOException e3) {
			throw e3;
		}
		conn.setRequestMethod("GET");
		conn.setConnectTimeout(5000);
		conn.setReadTimeout(10000);
		conn.setRequestProperty("Range", "bytes=" + position + "-"+length);
		conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
		//long length = conn.getContentLength();
		InputStream is = null;
		RandomAccessFile file = null;
		try {
			is = conn.getInputStream();
			try {
				file = new RandomAccessFile(path, "rwd");
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			try {
				file.setLength(length);
				file.seek(position);
			} catch (IOException e2) {
				throw e2;
			}
			int len;
			byte[] buffer = new byte[1024];
			while ((len = is.read(buffer)) != -1) {
				if (stopflag) {
					is.close();
					onCancelled();
					file.close();
					return null;
				}
				file.write(buffer, 0, len);
				currentPostion += len;
				onProgressChange(currentPostion, length);
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(positionFile);
					fos.write((currentPostion + "").getBytes());
					fos.flush();
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} catch (IOException e) {
					throw e;
				} finally {
					if (fos != null)
						fos.close();
				}
			}
			is.close();
			positionFile.delete();
			File res = new File(path);
			return res;
		} catch (IOException e) {
			throw e;
		} finally {
			try {
				if (is != null)
					is.close();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
			try {
				if (file != null)
					file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public void cancel() {
		stopflag = true;
		cancel(true);
	}
	
}
